package com.lagou.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

public class GroupChatNioClient {

    private SocketChannel socketChannel;
    private final static int PORT = 6667;
    private String name;
    private Selector selector;

    public GroupChatNioClient() {
        try {
            socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress("127.0.0.1", PORT));
            selector = Selector.open();
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            name = socketChannel.getLocalAddress().toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen () {
        try {
            while (true) {
                if (selector.select(100) > 0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey next = iterator.next();
                        if (next.isReadable()) {
                            SocketChannel channel = (SocketChannel) next.channel();
                            ByteBuffer allocate = ByteBuffer.allocate(1024);
                            channel.read(allocate);
                            System.out.println("接收到消息：" + new String(allocate.array()));
                        }
                        iterator.remove();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        GroupChatNioClient nioClient = new GroupChatNioClient();
        new Thread(() -> {
            nioClient.listen();
        }).start();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String s = scanner.nextLine();
            nioClient.socketChannel.write(ByteBuffer.wrap(s.getBytes()));
        }
    }
}
